# -*- coding: utf-8 -*-
'''
@File    :   aliASR.py
@Author  :   zz 
'''

from ..builder import ASREngines
from ..engineBase import BaseEngine
from typing import List, Optional

from digitalHuman.utils import AudioMessage, TextMessage
from digitalHuman.utils import logger

from dashscope.audio.asr import Recognition
import dashscope
from http import HTTPStatus
from digitalHuman.utils import AudioDecoder
from uuid import uuid4
import wave

__all__ = ["AliAPI"]


@ASREngines.register("AliAPI")
class AliAPI(BaseEngine):
    def checkKeys(self) -> List[str]:
        return ["KEY"]

    def setup(self):
        pass

    async def run(self, input: AudioMessage, **kwargs) -> Optional[AudioMessage]:
        try:
            key = self.cfg.KEY if self.cfg.KEY else None

            uuid_str = uuid4()
            file_path = f"outputs/asr_{uuid_str}.wav"
            file_path_covert = f"outputs/asr_{uuid_str}_c.wav"
            with wave.open(file_path, "wb") as wav_file:
                wav_file.setnchannels(1)  # Set the number of channels (mono)
                wav_file.setsampwidth(2)  # Set the sample width (bytes per sample)
                wav_file.setframerate(input.sampleRate)  # Set the frame rate (samples per second)
                wav_file.writeframes(input.data)  # Write the audio bytes
            audio_decoder = AudioDecoder()
            audio_decoder.resample_wav_file(file_path, file_path_covert)

            dashscope.api_key = key
            print("------------------------调用阿里云语音转文字---------------------")
            recognition = Recognition(model='paraformer-realtime-v2',
                                      format='wav',
                                      sample_rate=16000,
                                      callback=None)
            result = recognition.call(file_path_covert)
            stt_str = ""
            if result.status_code == HTTPStatus.OK:
                for sentence in result.get_sentence():
                    stt_str = stt_str + sentence['text']
                print('Recognition done,result: ' + stt_str)
                print("------------------------调用结束---------------------")
            else:
                print('Error: ', result.message)

            message = TextMessage(data=stt_str)
            return message
        except Exception as e:
            logger.error(f"[ASR] Engine run failed: {e}")
            return None
